package com.kgc.cart.interceptor;

import com.kgc.cart.jedis.JedisClient;
import com.kgc.entity.TbUser;
import com.kgc.utils.CookieUtils;
import com.kgc.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JedisClient jedisClient;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = CookieUtils.getCookieValue(httpServletRequest, "USERTOKENID", true);
        String s=null;
        String url = httpServletRequest.getRequestURL().toString();
        // token判断是否为空！
        if (StringUtils.isEmpty(token)){
           httpServletResponse.sendRedirect("http://localhost:8084/user/showLogin?url="+url);
           return false;
        }
        s = jedisClient.get("USERTOKENID:"+token);

        if (s==null){
            httpServletResponse.sendRedirect("http://localhost:8084/user/showLogin?url="+url);
            return false;
        }

        TbUser tbUser = JsonUtils.jsonToPojo(s, TbUser.class);
        httpServletRequest.setAttribute("user",tbUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
